// 引入库
import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'
// 创建实例
const service = axios.create({
  // 基准路径URL = baseurl+requesturl
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  // 请求超时5秒
  timeout: 5000 // request timeout
})

// 请求拦截
service.interceptors.request.use(config => {
  if (store.getters.token) {
    const sj = localStorage.getItem('sj')
    if (Date.now() - sj > 10000000) {
      store.dispatch('user/logout')
      router.push('/login')
      return Promise.reject(new Error('token 已超时，请重新登陆'))
    }
    config.headers.Authorization = `Bearer ${store.getters.token}`
  }
  return config
})

// 响应拦截
service.interceptors.response.use(res => {
  console.log(res)
  // 网络请求成功
  const { success, message, data } = res.data
  // success ==ture 操作成功
  if (success) {
    console.log(message)
    return data
  } else {
    // success ==falas
    console.log(message)
    Message.error(message)
    return Promise.reject(new Error(message))
  }
}, err => {
  // 网络请求失败
  console.dir(err)
  if (err.response.data.code === 10002) {
    console.log(48)
    store.dispatch('user/logout')
    router.push('/login')
  }
  Message.error(err.message)

  return Promise.reject(new Error(err.message))
})

export default service
